<template>
  <div class="after-sale-container">
    <!-- 搜索栏 -->
    <div class="search-wrapper">
      <el-input
        v-model="searchText"
        placeholder="请输入售后名称"
        style="width: 300px"
        clearable
        @keyup.enter="handleSearch">
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>搜索
      </el-button>
      <el-button type="success" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%">
      <el-table-column prop="id" label="id" width="80" align="center" />
      <el-table-column prop="afterSaleName" label="售后名称" min-width="120" align="center" />
      <el-table-column prop="type" label="类型" width="120" align="center" />
      <el-table-column prop="content" label="内容" width="200" align="center" />
      <el-table-column prop="reply" label="回复" width="200" align="center" />
      <el-table-column prop="createBy" label="创建人" width="120" align="center" />
      <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
      <el-table-column prop="updateBy" label="更新人" width="120" align="center" />
      <el-table-column prop="updateTime" label="更新时间" width="180" align="center" />
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-popconfirm
            title="确定删除该售后记录吗？"
            @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="danger" link>
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add'? '添加售后' : '编辑售后'"
      width="500px"
      @close="resetForm">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px">
        <el-form-item label="售后名称" prop="afterSaleName">
          <el-input v-model="formData.afterSaleName" placeholder="请输入售后名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择类型">
            <el-option label="退货" value="退货" />
            <el-option label="换货" value="换货" />
            <!-- 可根据实际情况添加更多类型选项 -->
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="formData.content" type="textarea" placeholder="请输入内容描述" />
        </el-form-item>
        <el-form-item label="回复" prop="reply">
          <el-input v-model="formData.reply" type="textarea" placeholder="请输入回复内容" />
        </el-form-item>
        <el-form-item label="创建人" prop="createBy">
          <el-input v-model="formData.createBy" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="formData.createTime"
            type="datetime"
			value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择创建时间"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="更新人" prop="updateBy">
          <el-input v-model="formData.updateBy" placeholder="请输入更新人" />
        </el-form-item>
        <el-form-item label="更新时间" prop="updateTime">
          <el-date-picker
            v-model="formData.updateTime"
            type="datetime"
			value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择更新时间"
            style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { Search, Plus, Edit, Delete, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { get, post } from '@/api/api'

// 数据列表
const tableData = ref([])
const loading = ref(false)
const searchText = ref('')

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const submitLoading = ref(false)
const formRef = ref()
const formData = reactive({
  id: null,
  afterSaleName: '',
  type: '',
  content: '',
  reply: '',
  createBy: '',
  createTime: null,
  updateBy: '',
  updateTime: null
})

// 表单校验规则
const rules = {
  afterSaleName: [{ required: true, message: '请输入售后名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  content: [{ required: true, message: '请输入内容描述', trigger: 'blur' }],
  reply: [{ required: true, message: '请输入回复内容', trigger: 'blur' }],
  createBy: [{ required: true, message: '请输入创建人', trigger: 'blur' }],
  createTime: [{ required: true, message: '请选择创建时间', trigger: 'change' }],
  updateBy: [{ required: true, message: '请输入更新人', trigger: 'blur' }],
  updateTime: [{ required: true, message: '请选择更新时间', trigger: 'change' }]
}

// 获取数据列表
const fetchData = async () => {
  loading.value = true
  try {
    const res = await get('/afterSales/page', {
      pageNum: 1, // 可根据实际情况修改分页参数
      pageSize: 10, // 可根据实际情况修改分页参数
      name: searchText.value
    })
    console.log('售后列表数据:', res)
    if (res && res.data) {
      tableData.value = res.data.records || []
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  fetchData()
}

// const resetForm=()=>{
// 	dialogVisible.value = false;
// 	console.log("close");
// }
// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  resetForm();
  // 确保表单被完全重置
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  })
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  formData.id = row.id
  formData.afterSaleName = row.afterSaleName
  formData.type = row.type
  formData.content = row.content
  formData.reply = row.reply
  formData.createBy = row.createBy
  formData.createTime = row.createTime
  formData.updateBy = row.updateBy
  formData.updateTime = row.updateTime
}

// 删除
const handleDelete = async (id) => {
  try {
    const res = await post('/afterSales/remove', { id: id })
    if (res) {
      ElMessage.success('删除成功')
      fetchData()
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 构造提交数据
        const submitData = {
          id: formData.id,
          afterSaleName: formData.afterSaleName,
          type: formData.type,
          content: formData.content,
          reply: formData.reply,
          createBy: formData.createBy,
          createTime: formData.createTime,
          updateBy: formData.updateBy,
          updateTime: formData.updateTime
        }

        console.log('提交的数据:', submitData)

        const url = dialogType.value === 'add'? '/afterSales/save' : '/afterSales/update'
        
		console.log(submitData);
		const res = await post(url, submitData)
        console.log('服务器响应:', res)

        if (res) {
          ElMessage.success(dialogType.value === 'add'? '添加成功' : '更新成功')
          dialogVisible.value = false
          fetchData()
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}


// 初始化
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.after-sale-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}
</style>